package com.mijie.homi.service.user;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mijie.homi.common.constant.TypeCode;
import com.mijie.homi.common.domain.PushMessage;
import com.mijie.homi.common.domain.Upgrade;
import com.mijie.homi.common.domain.user.DeviceInfo;
import com.mijie.homi.dao.user.DeviceInfoDao;
import com.mijie.homi.service.common.MixService;
import com.mijie.homi.service.notify.PushService;
import com.mijie.util.DateUtil;
import com.mijie.util.Helper;

@Service
public class DeviceInfoService {

	@Autowired
	private DeviceInfoDao dao;
	@Autowired
	private MixService mixService;
	@Autowired
	private PushService pushService;
	private Logger logger = Logger.getLogger(DeviceInfoService.class);
	
	
	@Transactional(rollbackFor={Exception.class})
	public int addOrUpdateDeviceInfo(DeviceInfo device){
		return dao.addOrUpdateDeviceInfo(device);
	}
	
	public DeviceInfo getDeviceInfo(String deviceId){
		return dao.getDeviceInfo(deviceId);
	}
	
	public int incrDeviceUnreadNotifyCount(String deviceId,int num){
		return dao.incrDeviceUnreadNotifyCount(deviceId, num);
	}

	public void pushRemindNotify(){
		Map<String,Upgrade> cacheForUpgrade = new HashMap<String,Upgrade>();
		int limit = 300;
		int offset = 0;
		int dayIntervalForNotifyUpgrade = 3;
		int dayIntervalForNotifyLogin = 3;
		int unloginDay = 0;
		List<DeviceInfo> list = null;
		Upgrade upgrade =  null;
		List<PushMessage> pushList = new ArrayList<PushMessage>(limit);
		PushMessage message = null;
		Date current = new Date();
		while(true){
			list = dao.listIOSDevice(offset,limit);
			if(list==null || list.isEmpty()) break;
			
			pushList.clear();
			
			offset += limit;
			for(DeviceInfo client : list){
				//notify login
				unloginDay = DateUtil.getDayInterval(client.getRecentLoginAt(), new Date());
				
				if(unloginDay>=dayIntervalForNotifyLogin){
					if(client.getRecentNotifyLoginAt()==null || (client.getRecentNotifyLoginAt() != null &&
					   DateUtil.getDayInterval(client.getRecentNotifyLoginAt(), new Date()) >= dayIntervalForNotifyLogin)){
						message = new PushMessage();
						message.setContentType(TypeCode.SYSTEM_MESSAGE);
						message.setDestinationDeviceId(client.getDeviceId());
						message.setId(Helper.genUUID());
						message.setIdx(System.currentTimeMillis());
						message.setContent("您已经有"+unloginDay+"天没登陆哈米了，请保持每天登陆一次，这样将有助于我们更好地为您服务！");
						pushList.add(message);
						logger.info("add to push notify queue,unloginDay:"+unloginDay);
						dao.updateNotifyLoginAt(client.getDeviceId(), current);
					}
				}
				
				//notify upgrade
				upgrade = cacheForUpgrade.get(client.getAppVer());
				if(upgrade==null){
					upgrade = mixService.getIphoneUpgrade(client.getAppVer());
					if(upgrade!=null) cacheForUpgrade.put(client.getAppVer(), upgrade);
				}
				
				if(upgrade!= null){
					if (client.getRecentNotifyUpgradeAt()==null || (client.getRecentNotifyUpgradeAt() != null &&
						DateUtil.getDayInterval(client.getRecentNotifyUpgradeAt(), new Date()) >= dayIntervalForNotifyUpgrade)){
						message = new PushMessage();
						message.setContentType(TypeCode.SYSTEM_MESSAGE);
						message.setDestinationDeviceId(client.getDeviceId());
						message.setId(Helper.genUUID());
						message.setIdx(System.currentTimeMillis());
						message.setContent("哈米"+upgrade.getVersionName()+"新版本已发布，优化了现有体验和增加了功能点，请下载更新，体验更佳！");
						pushList.add(message);
						logger.info("add to push notify queue,have new version:"+upgrade.getVersionName());
						dao.updateNotifyUpdateAt(client.getDeviceId(), current);
					}
				}
			}//end for
			
			logger.info("##notify push list size:"+pushList.size()+",offset:"+offset+",limit:"+limit);
			if(pushList.size()>0){
				pushService.batchAddToPushQueue(pushList);
			}
		}//end while
	}
	
}
